package uml.GUI;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import uml.controller.Controller;
import uml.eventsystem.IObserver;
import uml.eventsystem.ISubject;
import uml.eventsystem.SubjectImpl;
import uml.eventsystem.events.UMLEventId;

public class CommandRibbon extends JMenuBar implements ActionListener, ISubject
{
	/**
	 * Lookup table 
	 */
	HashMap<String, UMLEventId> eventIDLookupTable;
	SubjectImpl m_subjImpl;
	/**
	 * Creates a default <tt>CommandRibbon</tt> with all menus already initialized
	 * @param controller
	 */
	public CommandRibbon (Controller controller)
	{
		m_subjImpl = new SubjectImpl();
		registerEvents(controller);
		add(initFileMenu());
	}
	/**
	 * Registsers observer for all events this class uses
	 * @param controller
	 */
	private void registerEvents(IObserver observer) 
	{
		
		addObserver(observer, UMLEventId.APPLICATION_EXIT);
	}
	@Override
	public void actionPerformed(ActionEvent e) 
	{
		String menuName = e.getActionCommand();
		UMLEventId event = eventIDLookupTable.get(menuName);
		notifyObservers(event);
	}
	/**
	 * Adds a new menu option to the menu with its name name and <tt>UMLEventId</tt> event
	 * @param name
	 * @param event
	 * @param menu
	 */
	private void addMenuItem(String name, UMLEventId event, JMenuItem menu)
	{
		JMenuItem item = new JMenuItem(name);
		item.addActionListener(this);
		eventIDLookupTable.put(name, event);
		menu.add(item);
	}

	@Override
	public void addObserver(IObserver observer, UMLEventId eventId) 
	{
		m_subjImpl.addObserver(observer, eventId);
	}

	@Override
	public void removeObserver(IObserver observer, UMLEventId eventId) 
	{
		m_subjImpl.removeObserver(observer, eventId);
	}

	@Override
	public void notifyObservers(UMLEventId eventId) 
	{
		m_subjImpl.notifyObservers(eventId);
	}	
	/**
	 * Creates all the file menus
	 * @return
	 */
	private JMenu initFileMenu() 
	{
		eventIDLookupTable = new HashMap<String, UMLEventId>();
		JMenu j = new JMenu("File");
		addMenuItem("Exit", UMLEventId.APPLICATION_EXIT, j);
		return j;
	}
}
